// comm.hpp
#pragma once
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>
#include <unistd.h>
using namespace std;

bool GetQueryString(std::string &query_string)
{
    bool result = false;
    std::string method = getenv("METHOD");
    cerr << "Debug Method: " << method << endl;

    if (method == "GET")
    {
        query_string = getenv("QUERY_STRING");
        result = true;
        cerr << "Get Debug Query_string: " << query_string << endl;
    }
    else if (method == "POST")
    {
        int content_length = std::stoi(getenv("CONTENT_LENGTH"));
        char ch = 0;
        while (content_length)
        {
            read(0, &ch, 1);
            query_string += ch;
            --content_length;
        }
        result = true;
        cerr << "Post Debug Query_string: " << query_string << endl;
    }
    else
    {
        result = false;
    }
    return result;
}

void CutQueryString(std::vector<std::pair<std::string, std::string>> &out, std::string &in)
{
    size_t pos1 = 0;
    while (pos1 != std::string::npos)
    {
        size_t pos2 = in.find("&", pos1);
        std::string tmp;
        if (pos2 == std::string::npos)
        {
            tmp = in.substr(pos1);
        }
        else
        {
            tmp = in.substr(pos1, pos2 - pos1);
        }
        size_t pos3 = tmp.find("=");
        std::string key = tmp.substr(0, pos3);
        std::string value = tmp.substr(pos3 + 1);
        out.push_back({key, value});
        pos1 = (pos2 == std::string::npos) ? pos2 : pos2 + 1;
    }
}